import 'dart:convert';
import 'dart:typed_data';

import 'package:hex/hex.dart';
import 'package:pointycastle/api.dart';
import 'package:pointycastle/digests/sm3.dart';
import 'package:pointycastle/macs/hmac.dart';

class EncryptUtils {

  static const String KEY = 'ams';

  static String encrypt(Map<String, dynamic> object, int time) {
    String key = '$time$KEY';
    String input = jsonEncode(object);
    return hmacSm3(key, input.replaceAll(r'\', ''));
  }

  static Map<String, dynamic> sortMapByKey(Map<String, dynamic> unsortedMap) {
    var sortedKeys = unsortedMap.keys.toList()..sort();
    var sortedMap = <String, dynamic>{};
    for (var key in sortedKeys) {
      sortedMap[key] = unsortedMap[key];
    }
    return sortedMap;
  }

  static String hmacSm3(String key, String srcStr) {
    var keyParam = KeyParameter(utf8.encode(key));
    var srcData = utf8.encode(srcStr);
    var digest = SM3Digest();

    var hmac = HMac(digest, 64);
    hmac.init(keyParam);
    hmac.update(srcData, 0, srcData.length);
    var result = Uint8List(hmac.macSize);
    hmac.doFinal(result, 0);

    return HEX.encode(result);
  }
}